<script>
	import store from '@/store';
	// #ifdef APP-PLUS
	import {
		AndroidTTSVoice
	} from "@/uni_modules/android-utils"
	// #endif

	export default {
		//监听路由变化，实现路由拦截，实现全局路由守卫
		// watch: {
		// 	$route(to, from) {
		// 		let token = uni.getStorageSync('token')
		// 		// vuex存储token
		// 		uni.$u.vuex('vuex_token', token);
		// 		if (to.path === '/pages/tabBar/scene/index' && (token == '' || token == null)) {
		// 			uni.showModal({
		// 				title: "提示",
		// 				content: '该功能需要登陆后使用，是否前往登录？',
		// 				success: function(res) {
		// 					if (res.confirm) {
		// 						console.log('用户点击确定');
		// 						self.$router.push('/pages/login/index');
		// 					} else if (res.cancel) {
		// 						console.log('用户点击取消');
		// 					}
		// 				}
		// 			})
		// 			// 如果需要登录验证且未登录，则跳转到登录页
		// 		}
		// 		if (to.path === '/pagesA/scene/alert/index' && (token == '' || token == null)) {
		// 			// 如果需要登录验证且未登录，则跳转到登录页
		// 			this.$router.push('/pages/login/index');
		// 		}
		// 		if (to.path === '/pagesA/scene/alert/index' && (token == '' || token == null)) {
		// 			// 如果需要登录验证且未登录，则跳转到登录页
		// 			this.$router.push('/pages/login/index');
		// 		}
		// 	}
		// },
		beforeDestroy() {
			this.$mqttTool.unsubscribe('/notify/alert/web/push/' + getUserId());
		},

		onLaunch: function() {
			console.log('App Launch');
			// 判断用户是否首次打开
			var isFirstOpen = uni.getStorageSync('isFirstOpen');
			// 如果isFirstOpen不存在，说明是首次打开系统
			if (!isFirstOpen) {
				// 执行首次打开系统的逻辑，比如显示弹窗
				uni.reLaunch({
					url: '/pagesB/login/firstOpen'
				});
			}
			//else {
			// 	// 如果不是首次打开系统，直接跳转到登录页
			// 	uni.reLaunch({
			// 		url: '/pages/login/index'
			// 	});
			// 	// uni.setStorageSync('isFirstOpen', false);
			// }
			// #ifdef MP-WEIXIN
			this.checkWeChatUpdate();
			// #endif
		},
		onShow: function() {
			this.$watch('$route', (to, from) => {
				this.checkLoginStatus(to);
			});
			let token = uni.getStorageSync('token');
			if (token) {
				this.connectMqtt();
			}
			console.log('App Show');
		},
		mounted() {
			// #ifdef H5
			if (window.speechSynthesis) {
				window.speechSynthesis.getVoices(); // 触发引擎初始化
			}
			// #endif
		},
		methods: {
			checkLoginStatus(route) {
				let token = uni.getStorageSync('token');
				if ((route.path === '/pages/tabBar/scene/index' || route.path === '/pages/tabBar/alert/index') && (token ==
						'' || token == null)) {
					uni.showModal({
						title: this.$tt('common.tips'),
						content: this.$tt('common.loginTips'),
						cancelText: this.$tt('common.cancel'),
						confirmText: this.$tt('common.confirm'),
						success: (res) => {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.navigateTo({
									url: '/pagesB/login/waitLogin'
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			},
			checkWeChatUpdate() {
				const updateManager = uni.getUpdateManager();
				updateManager.onCheckForUpdate((res) => {
					if (res.hasUpdate) {
						updateManager.onUpdateReady(() => {
							uni.showModal({
								title: this.$tt('system.updateTip'),
								content: this.$tt('system.updateReady'),
								success: (res) => {
									// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
									if (res.confirm) {
										updateManager.applyUpdate()
									}
								}
							})
						});
						// 新的版本下载失败
						updateManager.onUpdateFailed(() => {
							uni.showModal({
								title: this.$tt('system.updateTip'),
								content: this.$tt('system.updateFailed'),
								showCancel: false
							})
						})
					}
				});
			},
			//订阅主题
			async connectMqtt() {
				if (this.$mqttTool.client === null) {
					await this.$mqttTool.connect(this.vuex_token);
				}
				this.mqttCallback();
				this.$mqttTool.subscribe('/notify/alert/web/push/' + this.profile.userId);
			},
			//实时告警信息
			mqttCallback() {
				this.$mqttTool.client.on('message', (topic, message) => {
					try {
						message = JSON.parse(message.toString());
						if (message.showDialog === 1) {
							// 显示模态框
							uni.showModal({
								title: message.title,
								content: message.content,
								showCancel: false,
								confirmText: this.$tt('common.confirm'),
								success: () => {
									// 用户点击确认后再尝试语音播报（用户交互触发）
									// #ifdef H5
									this.speakMessage(message);
									// #endif
								}
							});
							// #ifdef APP-PLUS
							this.speakApp(message);
							// #endif

							// #ifdef MP-WEIXIN
							// 小程序播放语音
							this.openVoice(message);
							// #endif
							// 震动
							this.onFeedTap();
						}
					} catch (e) {
						console.error('处理MQTT消息出错:', e);
					}
				});
			},
			//震动
			onFeedTap() {
				let platform = uni.getSystemInfoSync().platform
				// #ifdef APP-PLUS
				if (platform == "ios") {
					let UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
					let impact = new UIImpactFeedbackGenerator();
					impact.prepare();
					impact.init(1);
					impact.impactOccurred();
				} else {
					uni.vibrateLong();
				}
				// #endif
				// #ifdef MP-WEIXIN || H5
				uni.vibrateLong();
				// #endif
			},
			//小程序使用
			openVoice(message) {
				let _this = this;
				const plugin = requirePlugin('WechatSI');
				const text = `${message.title}。${message.content}`;
				plugin.textToSpeech({
					lang: 'zh_CN',
					tts: true,
					content: text,
					success: function(res) {
						_this.speechPlay(res.filename)
					},
					fail: function(res) {
						console.log('fail tts', res);
					},
					complete: function(res) {
						console.log('complete tts', res);
					}
				});
			},
			speechPlay(src) {
				const innerAudioContext = wx.createInnerAudioContext();
				if (src == '') {
					return;
				}
				innerAudioContext.autoplay = true;
				innerAudioContext.src = src; //设置音频地址
				innerAudioContext.play(); //播放音频
			},

			// H5端使用
			speakMessage(message) {
				// 检测是否可以自动播放语音
				this.checkSpeechPermission().then(canSpeak => {
					if (canSpeak) {
						this.speakMessage(message);
					} else {
						console.log('需要用户交互才能播放语音');
					}
				});
				if (!window.speechSynthesis) {
					console.error("浏览器不支持语音合成API");
					return;
				}
				const text = `${message.title}。${message.content}`;
				// 停止任何正在进行的语音
				window.speechSynthesis.cancel();
				const utterance = new SpeechSynthesisUtterance(text);
				utterance.lang = 'zh-CN';
				utterance.rate = 0.9;
				utterance.pitch = 1.0;
				utterance.volume = 1.0;
				utterance.onend = () => {
					console.log('语音播报结束');
				};
				utterance.onerror = (event) => {
					// 可以在这里提示用户点击按钮启用语音
					uni.showToast({
						title: '请点击屏幕启用语音',
						icon: 'none'
					});
				};
				window.speechSynthesis.speak(utterance);
			},
			// 检查语音权限
			checkSpeechPermission() {
				return new Promise(resolve => {
					// 尝试播放一个简短的测试语音
					const testUtterance = new SpeechSynthesisUtterance('');
					testUtterance.onend = () => resolve(true);
					testUtterance.onerror = () => resolve(false);
					// 如果没有立即报错，认为有权限
					setTimeout(() => resolve(true), 100);
				});
			},
			// app
			speakApp(message) {
				const text = `${message.title}。${message.content}`;
				const tts = new AndroidTTSVoice(function(state) {
					if (state) {
						tts.listenerVoiceState(function(b) {
							console.log(b)
						})
						tts.speak('你的设备' + `${message.title}。${message.content}`);
					}
				});
			},
		},
		onHide: function() {
			console.log('App Hide');
		},
	};
</script>

<style lang="scss">
</style>